<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 刘洪兆0720
  Date: 2022/5/1
  Time: 9:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上机考试系统</title>

    <style>
        .btn {
            color: white;
            text-decoration: none;
            cusor: pointer;
            background: #0066ff;
            border-radius: 4px;
            padding: 3px 6px;
        }

        ul.pagination {
            display: inline-block;
            padding: 0;
            margin: 0;
        }

        ul.pagination li {
            display: inline;
        }

        ul.pagination li a {
            color: black;
            float: left;
            padding: 8px 16px;
            text-decoration: none;
        }
    </style>
</head>
<body>
<jsp:include page="admin_head.jsp"></jsp:include>

<!-- 教师添加的模态框 -->
<div class="modal fade" id="teaAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">添加教师</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">学工号</label>
                        <div class="col-sm-10">
                            <input type="text" name="t_username" class="form-control" id="teaNumber_add_input"
                                   placeholder="学工号">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" name="t_name" class="form-control" id="teaName_add_input"
                                   placeholder="真实姓名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="text" name="t_pwd" class="form-control" id="teaPassword_add_input"
                                   placeholder="初始密码">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">类型</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="t_manager" id="isAdmin1_add_input" value="1"> 管理员
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="t_manager" id="isAdmin_add_input" value="0" checked="checked">教师
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="tea_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 教师修改的模态框 -->
<div class="modal fade" id="teaUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">教师修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">工号</label>
                        <div class="col-sm-10">
                            <input type="text" name="t_username" class="form-control" id="teaNumber_update_input"
                                   placeholder="学工号">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" name="t_name" class="form-control" id="teaName_update_static"
                                   placeholder="真实姓名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <span>不可修改</span>
                            <input type="hidden" name="t_pwd" class="form-control" id="teaPassword_update_input"
                                   placeholder="teaPassword">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">类型</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="t_manager" id="isAdmin1_update_input" value="1"> 管理员
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="t_manager" id="isAdmin2_update_input" value="0"
                                       checked="checked"> 教师
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="tea_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 批量导入教师数据模态框 -->
<div class="modal fade" id="importTeaData" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">批量导入</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" enctype="multipart/form-data" id="uploadForm">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">文件名</label>
                        <div class="col-sm-10">
                            <input type="file" name="file" class="form-control" id="file" placeholder="文件名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary" id="tea_import_btn">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 搭建显示页面 -->
<div class="container">
    <!-- 标题 -->
    <!-- 按钮 -->
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="tea_add_modal_btn" style="position: relative;right: 80px;">新增</button>
            <button class="btn btn-primary" id="tea_adds_modal_btn" style="position: relative;right: 50px;">批量导入
            </button>
            <button class="btn btn-danger" id="tea_delete_all_btn" style="position: relative;right: 10px;">批量删除</button>
        </div>
    </div>

    <!-- 显示表格数据 -->
    <div class="row" style="margin-top: 30px">
        <div class="col-md-12">
            <strong style="display:block;margin-left: 20px; font-size: 18px">全部教师信息</strong>
            <!--分页文字信息  -->
            <%--            <div class="col-md-8 text-start" id="page_info_area" style="margin-bottom: 10px;margin-left:5px;margin-top:20px;font-size: 15px;"></div>--%>

            <table class="table table-responsive table-bordered table-striped table-hover" id="teas_table">
                <thead class="table-light">
                <tr>
                    <th><input type="checkbox" id="check_all"/></th>
                    <th>序号</th>
                    <th>工号</th>
                    <th>姓名</th>
                    <th>密码(不可修改)</th>
                    <th>类型</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>

    <!--分页-->
    <div id="pageDiv"></div>
    <!--end 分页-->
</div>
</body>

<script type="text/javascript">
    var totalRecord, currentPage;

    //1、页面加载完成以后，直接去发送ajax请求,要到分页数据
    $(function () {
        //去首页
        to_page(1);
    });

    function saveExcel() {
        if ($("input[name='file']").val().length == 0) {
            alert("请选择文件");
            return false;
        }
        return true;
    }

    function to_page(pageNum) {
        $.ajax({
            url: "${path}/getAllTeacher",
            data: {"pageNum": pageNum},
            type: "GET",
            success: function (result) {
                //1、解析并显示教师数据
                build_teas_table(result);
            }
        });
    }

    // 填充表格数据
    function build_teas_table(result) {
        var total = result.extend.pageInfo.total;//页总数
        var pageNum = result.extend.pageInfo.pageNum;//页号
        var pageSize = result.extend.pageInfo.pageSize;//页大小
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;

        //清空table表格
        $("#teas_table tbody").empty();
        var teas = result.extend.pageInfo.list;
        $.each(teas, function (index, item) {
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>");
            var idx = $("<td></td>").append((index + 1));
            var teaNumber = $("<td></td>").append(item.t_username);
            var teaNameTd = $("<td></td>").append(item.t_name);
            var teaPasswordTd = $("<td></td>").append(item.t_pwd);
            var type = $("<td></td>").append(item.t_manager == 1 ? "管理员" : "教师");

            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
            //为编辑按钮添加一个自定义的属性，来表示当前教师id
            editBtn.attr("edit-id", item.t_username);
            var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            //为删除按钮添加一个自定义的属性来表示当前删除的教师id
            delBtn.attr("del-id", item.t_username);
            var btnTd = $("<td></td>").append(editBtn).append("\t").append(delBtn);

            //append方法执行完成以后还是返回原来的元素
            $("<tr></tr>").append(checkBoxTd)
                .append(idx)
                .append(teaNumber)
                .append(teaNameTd)
                .append(teaPasswordTd)
                .append(type)
                .append(btnTd)
                .appendTo("#teas_table tbody");
        });

        if (total < 6) {
            return;
        }
        //开启分页组件
        trainschemesPage(total, pageNum, pageSize);
    }

    /**
     * layui的分页插件
     * @param total 总数
     * @param pageNum   当前页
     * @param pageSize  页大小
     */
    function trainschemesPage(total, pageNum, pageSize) {
        //使用layui的分页插件
        layui.use(['laypage', 'layer'], function () {
            var laypage = layui.laypage;

            //执行一个laypage实例
            laypage.render({
                elem: 'pageDiv', //注意，这里的 test1 是 ID，不用加 # 号
                count: total, //数据总数，从服务端得到
                limit: pageSize,//每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。
                curr: pageNum,//当前页号
                limits: [6, 10, 15, 20],
                layout: ['limit', 'prev', 'page', 'next', 'skip', 'count'],//显示哪些分页组件
                jump: function (obj, first) {//点击页号的时候执行的函数
                    if (!first) {//首次不执行(点击的时候才执行)
                        to_page(obj.curr)//执行查询分页函数(这个函数必须写在这里)
                    }
                }
            });
        });
    }

    //清空表单样式及内容
    function reset_form(ele) {
        $(ele)[0].reset();
        //清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    //点击新增按钮弹出模态框。
    $("#tea_add_modal_btn").click(function () {
        //清除表单数据（表单完整重置（表单的数据，表单的样式））
        reset_form("#teaAddModal form");
        //弹出模态框
        $("#teaAddModal").modal({
            backdrop: "static"
        });
    });

    //点击保存，保存教师。
    $("#tea_save_btn").click(function () {
        //1. 发送ajax请求保存教师
        //serialize() 方法通过序列化表单值，创建 URL 编码文本字符串。
        $.ajax({
            url: "${path}/addTeacher",
            type: "POST",
            data: $("#teaAddModal form").serialize(),
            success: function (result) {

                if (result.code == 100) {
                    //教师保存成功；
                    //1、关闭模态框
                    $("#teaAddModal").modal('hide');

                    //2、来到最后一页，显示刚才保存的数据
                    //发送ajax请求显示最后一页数据即可
                    to_page(totalRecord);
                } else {
                    //显示失败信息
                    alert(result.extend.va_msg);
                }
            }
        });
    });

    //点击批量导入按钮弹出模态框。
    $("#tea_adds_modal_btn").click(function () {
        //清除表单数据（表单完整重置（表单的数据，表单的样式））
        reset_form("#importTeaData form");
        //弹出模态框
        $("#importTeaData").modal({
            backdrop: "static"
        });
    });

    //点击批量按钮，保存教师。
    $("#tea_import_btn").click(function () {
        saveExcel();
        //1、发送ajax请求保存教师
        //serialize() 方法通过序列化表单值，创建 URL 编码文本字符串。
        $.ajax({
            url: "${path}/saveTeaExcel",
            type: "POST",
            cache: false,
            data: new FormData($('#uploadForm')[0]),
            processData: false,
            contentType: false,
            success: function (data) {
                //教师保存成功；
                alert("批量导入成功！")
                //1、关闭模态框
                $("#importTeaData").modal('hide');
                to_page(1);
            },
            error: function (data) {
                alert("发生了未知错误啦！");
            }
        });
    });

    //1、我们是按钮创建之前就绑定了click，所以绑定不上。
    //1）、可以在创建按钮的时候绑定。    2）、绑定点击.live()
    //jquery新版没有live，使用on进行替代
    $(document).on("click", ".edit_btn", function () {
        //1、查出教师信息，显示教师信息
        getTea($(this).attr("edit-id"));

        //2、把教师的id传递给模态框的更新按钮
        $("#tea_update_btn").attr("edit-id", $(this).attr("edit-id"));
        $("#teaUpdateModal").modal({
            backdrop: "static"
        });
    });

    function getTea(id) {
        $.ajax({
            url: "${path}/admin_get_teacher?teaId=" + id,
            type: "GET",
            success: function (result) {
                console.log(result);
                var teaData = result.extend.teacher;
                $("#teaName_update_static").val(teaData.t_name);
                $("#teaNumber_update_input").val(teaData.t_username);
                $("#teaPassword_update_input").val(teaData.t_pwd);
                $("#teaUpdateModal input[name=t_manager]").val([teaData.t_manager]);
            }
        });
    }

    //点击更新，更新教师信息
    $("#tea_update_btn").click(function () {

        //2、发送ajax请求保存更新的教师数据
        $.ajax({
            url: "${path}/editTeacherInfo",
            type: "POST",
            data: $("#teaUpdateModal form").serialize(),
            success: function () {
                //1、关闭对话框
                $("#teaUpdateModal").modal("hide");
                //2、回到本页面
                to_page(currentPage);
            }
        });
    });

    //单个删除
    $(document).on("click", ".delete_btn", function () {
        //1、弹出是否确认删除对话框
        var teaName = $(this).parents("tr").find("td:eq(3)").text();
        var teaId = $(this).attr("del-id");
        if (confirm("确认删除【" + teaName + "】吗？")) {
            //确认，发送ajax请求删除即可
            $.ajax({
                url: "${path}/deleteTeacher",
                type: "GET",
                data: {"teaId": teaId},
                success: function () {
                    //回到本页
                    to_page(currentPage);
                }
            });
        }
    });

    //完成全选/全不选功能
    $("#check_all").click(function () {
        //attr获取checked是undefined;
        //我们这些dom原生的属性；attr获取自定义属性的值；
        //prop修改和读取dom原生属性的值
        $(".check_item").prop("checked", $(this).prop("checked"));
    });

    //check_item
    $(document).on("click", ".check_item", function () {
        //判断当前选择中的元素是否5个
        var flag = $(".check_item:checked").length == $(".check_item").length;
        $("#check_all").prop("checked", flag);
    });

    //批量删除
    $("#tea_delete_all_btn").click(function () {

        var teaNames = "";
        var del_ids = "";
        $.each($(".check_item:checked"), function () {
            //this
            teaNames += $(this).parents("tr").find("td:eq(3)").text() + ",";
            //组装员工id字符串
            del_ids += $(this).parents("tr").find("td:eq(2)").text() + "-";
        });

        //去除teaNames多余的,
        teaNames = teaNames.substring(0, teaNames.length - 1);
        //去除删除的id多余的-
        del_ids = del_ids.substring(0, del_ids.length - 1);
        if (confirm("确认删除【" + teaNames + "】吗？")) {
            //发送ajax请求删除
            $.ajax({
                url: "${path}/admin_delete_teachers?del_ids=" + del_ids,
                type: "GET",
                success: function (result) {
                    alert(result.msg);
                    //回到当前页面
                    to_page(currentPage);
                }
            });
        }
    });
</script>
</html>